package com.fly.doublecheck.api;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base32;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.fly.doublecheck.TotpUtils;
import com.fly.doublecheck.qr.QRCodeUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * QR
 * 
 * @author 00fly
 * @version [版本号, 2021年4月14日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Controller
public class ApiController
{
    @GetMapping("/{user}")
    public void index(@PathVariable String user, HttpServletResponse response)
        throws Exception
    {
        String uniqueId = DigestUtils.md5DigestAsHex(user.getBytes());
        String secret = new String(new Base32().encode(uniqueId.getBytes()));
        String content = TotpUtils.getQRCodeStr(user, secret);
        log.info("QR = {}", content);
        
        // 嵌入二维码的图片路径
        Resource resource = new ClassPathResource("qrCode/dog.jpg");
        String imgPath = resource.getFile().getAbsolutePath();
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, true);
        
        // 输出图象到页面
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
}
